<template>
  <!-- 咨询分类 -->
  <div id="infoList">
    <div>
      <h2 class="h2">
        <i class="el-icon-menu"></i>
        资讯分类
      </h2>
    </div>
    <div class="button">
      <!-- 新增按钮 -->
      <el-button
        size="small"
        icon="el-icon-folder-add"
        @click="toAdd"
        type="primary"
        >新增</el-button
      >
      <!-- //批量删除按钮 -->
      <el-button
        size="small"
        :disabled="multipleSelection.length == 0"
        plain
        icon="el-icon-delete"
        type="danger"
        @click="handleDelete(null)"
        >批量删除</el-button
      >
    </div>
    <el-table
      border
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="id" label="序号(id号)" width="90">
      </el-table-column>
      <el-table-column prop="name" label="分类名称" width="180">
        <template slot-scope="scope">
          <el-tag size="medium" type="warning" effect="dark">{{
            scope.row.name
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="分类简介" width="640">
      </el-table-column>
      <el-table-column prop="no" label="序号(no号)" width="90">
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            plain
            icon="el-icon-delete"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      :before-close="beforeClose"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <!-- 名称！ -->
        <el-form-item
          label="分类名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input
            v-model="form.name"
            autocomplete="off"
            placeholder="你需要一个分类名称"
          ></el-input>
        </el-form-item>
        <!-- 介绍！ -->
        <el-form-item
          label="分类简介"
          :label-width="formLabelWidth"
          prop="description"
        >
          <el-input
            type="textarea"
            :rows="3"
            placeholder="这个人很懒，什么都没留下……"
            v-model="form.description"
            autocomplete="off"
          >
          </el-input>
        </el-form-item>
        <!-- 序号！ -->
        <el-form-item label="序号" :label-width="formLabelWidth" prop="no">
          <el-input
            v-model.number="form.no"
            autocomplete="off"
            placeholder="请输入序号，仅限数字！"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toCancel()">取 消</el-button>
        <el-button type="primary" @click="toSave('ruleForm')">添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "../../utils/request";
export default {
  data() {
    return {
      // 多选
      multipleSelection: [],
      tableData: [],
      //模态框可见性  默认false不可见
      visible: false,
      //模态框的数据
      form: {},
      //表单控件标题的宽度
      formLabelWidth: "120px",
      //模态框的表头
      title: "录入分类信息",
      // 表单校验规则
      rules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        description: [
          { required: true, message: "请输入简介", trigger: "blur" },
        ],
        no: [{ required: true, message: "请输入序号", trigger: "blur" }],
      },
    };
  },
  computed: {},
  methods: {
    // 批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id);
    },
    // 删除
    handleDelete(id) {
      // id 就是要删除的分类的对象的id
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // await等待后面异步函数运行完毕，拿到响应的数据，然后返回
          let res;
          if (id) {
            res = await axios.get("/category/deleteById", { params: { id } });
          } else {
            res = await axios.post("/category/batchDelete", {
              ids: this.multipleSelection.toString(),
            });
          }
          this.$notify({
            title: res.status == 200 ? "成功" : "失败",
            message: res.statusText,
            type: res.status == 200 ? "success" : "error",
          });
          this.findAll();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //编辑
    handleEdit(row) {
      this.title = "编辑分类信息";
      this.form = { ...row };
      this.visible = true;
    },
    // 点击确定按钮
    toSave(formName) {
      this.$refs[formName].validate((valid) => {
        // 校验通过
        if (valid) {
          axios.post("/category/saveOrUpdate", this.form).then((res) => {
            console.log(res);
            if (res.status == 200) {
              //保存成功，关闭模态框，刷新数据
              this.$notify({
                title: "成功！",
                message: "保存成功",
                type: "success",
              });
              this.toCancel();
              this.findAll();
            } else {
              this.$notify.error({
                title: "失败",
                message: "保存失败",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //关闭模态框
    toCancel() {
      this.$refs["ruleForm"].resetFields();
      this.visible = false;
    },
    //模态框关闭之前
    beforeClose(done) {
      this.$refs["ruleForm"].resetFields();
      done();
    },
    //点击新增按钮
    toAdd() {
      this.form = {};
      this.visible = true;
      this.title = "新增分类信息";
    },
    //获取后台数据
    findAll() {
      axios.get("/category/findAll").then((res) => {
        this.tableData = res.data;
      });
    },
  },
  created() {
    //封装-获取后台数据函数
    this.findAll();
  },
  mounted() {},
};
</script>
<style scoped>
.h2 {
  margin-top: 0;
}
.button {
  margin-bottom: 5px;
}
</style>